/*
 * Unique Binary Search Trees II
Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

For example,
Given n = 3, your program should return all 5 unique BST's shown below.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
 */
package com.xinpan.exercise;

import java.util.ArrayList;

public class UniqueBST2 {
    public ArrayList<TreeNode> generateTrees(int n) {
        // Start typing your Java solution below
        // DO NOT write main() function
        return gTreeHelper(1, n);
    }
    public ArrayList<TreeNode> gTreeHelper(int s, int e)
    {
        ArrayList<TreeNode> res = new ArrayList<TreeNode>();
        
        if(s > e)
        {
            res.add(null);
            return res;
        }
        
        for(int i = s; i <= e; i++)
        {
            ArrayList<TreeNode> lTree = gTreeHelper(s, i-1);
            ArrayList<TreeNode> rTree = gTreeHelper(i+1, e);
            for(TreeNode l : lTree)
            {
                for(TreeNode r : rTree)
                {
                    TreeNode root = new TreeNode(i);
                    root.left = l;
                    root.right = r;
                    res.add(root);
                }
            }
        }
        return res;
    }
}
